package cn.tedu.lucky.draw.server.controller;

import cn.tedu.lucky.draw.server.common.result.JsonResult;
import cn.tedu.lucky.draw.server.protocol.po.Activity;
import cn.tedu.lucky.draw.server.protocol.query.ActivityQuery;
import cn.tedu.lucky.draw.server.service.IActivityService;
import org.springframework.batch.core.*;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
public class ActivityController {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job csvToDbJob;

    @Autowired
    private JobExplorer jobExplorer;

    @Autowired
    private IActivityService activityService;

    @PostMapping("/draw/activity/getAll")
    public JsonResult<List<Activity>> findAll(@RequestBody ActivityQuery activityQuery){
        List<Activity> activities = activityService.findAll(activityQuery);
        return JsonResult.ok(activities);
    }

    @PostMapping("/draw/activity/save")
    public JsonResult<String> save(@RequestBody Activity activity){
        activityService.save(activity);
        return JsonResult.ok("新增成功");
    }
    //批量导入任务
    @GetMapping("/activity/csvToDB")
    public JsonResult<String> csvToDB() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
        /**
         * jobExplorer 可以获取到当前运行的任务，以及上次作业的运行结果
         */
        JobParameters jobParameters =
                new JobParametersBuilder(new JobParameters(),jobExplorer)
                        .getNextJobParameters(csvToDbJob).toJobParameters();
        JobExecution run = jobLauncher.run(csvToDbJob, jobParameters);
        Long id = run.getId();
        return JsonResult.ok("任务ID:" + id);
    }
    //获取任务详情
    @PostMapping("/draw/activity/{id}")
    public JsonResult<Activity> getActivityById(@PathVariable("id") Long id){
        Activity activity = activityService.findActivityById(id);
        return JsonResult.ok(activity);
    }
}
